﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Connect
{
    /// <summary>
    /// Giao diện chính của Class .. Kết nối cơ sở dữ liệu
    /// </summary>
    public partial class ConnectPro : Form
    {
        Connection con = new Connection();

        public ConnectPro()
        {
            InitializeComponent();
           

        }

        private void lstNetWork_Click(object sender, EventArgs e)
        {
            Connect.IPConfig f = new Connect.IPConfig("ConnectPro");
            f.ShowDialog();
        }


        #region Lấy server cách 2
         private delegate string[] InternalDelegate();
        private InternalDelegate intlDelg;
        private delegate void AsyncDelegate(IAsyncResult result);
        private void CallBackMethod(IAsyncResult result)
        {
            try
            {
                    if (this.InvokeRequired)
                    {
                        this.Invoke(new AsyncDelegate(CallBackMethod), result);
                    }
                    string[] sqlServers = intlDelg.EndInvoke(result);
                    txtserver.Items.AddRange(sqlServers);
                    if (txtserver.Items.Count > 0)
                    {
                        txtserver.Sorted = true;
                        txtserver.SelectedIndex = 0;
                    }

            }
            catch (Exception)
            {
                return;
            }
          
        }
        private SQLInfoEnumerator sqlInfo;
        #endregion
       

        private void ConnectPro_Load(object sender, EventArgs e)
        {
            if (System.IO.File.Exists(Application.StartupPath + @"\Connection.bin"))
            {
                try
                {
                    txtserver.Text = con.rosv();
                    if (string.IsNullOrEmpty(con.rous()) == false)
                    {
                        sql.Checked = true;
                    }
                    txtUsername.Text = con.rous();
                    txtPassword.Text = con.rops();
                }
                catch (Exception)
                {

                }
                txtserver.DataSource = cnSQL.GetSQLServers();
                txtserver.DisplayMember = "ServerName";
                txtserver.ValueMember = "ServerName";
                //// Cách 2
               // sqlInfo = new SQLInfoEnumerator();
               //intlDelg = new InternalDelegate(sqlInfo.EnumerateSQLServers);
               // intlDelg.BeginInvoke(new AsyncCallback(CallBackMethod), intlDelg); 
                ////////////////////////////
            }
            else
            {
                MessageBox.Show("Not OK");
            }
            
        }

        private void refree_Click(object sender, EventArgs e)
        {
            ConnectPro_Load(sender, e);
        }

        private void sql_CheckedChanged(object sender, EventArgs e)
        {
            info.Enabled = (sql.Enabled == true) ? true : false;
            cmbDatabase.Enabled = false;
            lstTable.Enabled = false;
        }

        private void win_CheckedChanged(object sender, EventArgs e)
        {
            info.Enabled = (win.Enabled == true) ? false : true;
            cmbDatabase.Enabled = false;
            lstTable.Enabled = false;
        }

        private void ketnoi_Click(object sender, EventArgs e)
        {
            //Quyền Windows
            if (win.Checked == true)
            {
                cmbDatabase.Items.Clear();
                SqlConnection con = new SqlConnection("Data Source=" + txtserver.Text + ";Initial Catalog=master;Integrated Security=True;");
                SqlCommand cmd = new SqlCommand("SP_DATABASES", con);
                //SP_DATABASES là một store procedure có sẵn của sql server để lấy ra tất cả csdl trong sql server
                SqlDataReader reader;
                try
                {
                    con.Open();
                    reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        cmbDatabase.Items.Add(reader[0].ToString());
                    }
                    cmbDatabase.Enabled = true;
                    lstTable.Enabled = true;
                }
                catch
                {
                    MessageBox.Show("Lỗi kết nối tới máy chủ, vui lòng thử lại!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    if (con.State == ConnectionState.Open)
                        con.Close();

                    con.Dispose();
                    cmd.Dispose();


                }
            }

            //Quyền SQL Server
            if (sql.Checked==true)
            {
                cmbDatabase.Items.Clear();
                SqlConnection con = new SqlConnection("Data Source=" + txtserver.Text + ";Initial Catalog=master;User Id=" + txtUsername.Text + ";Password=" + txtPassword.Text + ";");
                SqlCommand cmd = new SqlCommand("SP_DATABASES", con);
                SqlDataReader reader;

                try
                {
                    con.Open();
                    reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        cmbDatabase.Items.Add(reader[0].ToString());
                    }
                    cmbDatabase.Enabled = true;
                    lstTable.Enabled = true;

                }
                catch
                {
                    MessageBox.Show("Lỗi kết nối tới máy chủ, vui lòng thử lại!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    if (con.State == ConnectionState.Open)
                        con.Close();
                   
                    con.Dispose();
                    cmd.Dispose();

                  
                }
            }
      
            
        }

        public SqlConnection GetConnect()
        {
            if (win.Checked==false)
                return new SqlConnection("Data Source=" + txtserver.Text.Trim() + ";Initial Catalog=" + cmbDatabase.SelectedItem.ToString().Trim() + ";User Id=" + txtUsername.Text.Trim() + ";Password=" + txtPassword.Text.Trim()+ ";");
            else
                return new SqlConnection("Data Source=" + txtserver.Text.Trim() + ";Initial Catalog=" + cmbDatabase.SelectedItem.ToString().Trim() + ";Integrated Security=True");
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                if (win.Checked == true)
                {
                    Connection.WriteFile(txtserver.Text.Trim(), cmbDatabase.Text.Trim(), "", "");
                }
                else
                {
                    Connection.WriteFile(txtserver.Text.Trim(), cmbDatabase.Text.Trim(), txtUsername.Text.Trim(), txtPassword.Text.Trim());
                }
                Close();
            }
        catch (Exception)
            {
                MessageBox.Show("Bạn vui lòng khởi động lại chương trình ! ", "Canh bao");
                Application.ExitThread();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                Close();
            }
            catch (Exception)
            {
                Application.Exit();
            }
        }

        private void cmbDatabase_SelectedIndexChanged(object sender, EventArgs e)
        {          
            btnOK.Enabled = true;

        }

      
        private void lstTable_Click(object sender, EventArgs e)
        {
            if ((cmbDatabase.Items.Count==0)||(string.IsNullOrEmpty(cmbDatabase.Text)==true))
            {
                return;
            }
            Connect.Table f = new Connect.Table("ConnectPro",cnSQL.GetTable(GetConnect()));
            f.ShowDialog();
        }

        private void ConnectPro_HelpButtonClicked(object sender, CancelEventArgs e)
        {
            // Hiển thị thanh công cụ
            Connect.MiniMenu f = new Connect.MiniMenu();
            f.Show();
            int desksHeights = Screen.PrimaryScreen.Bounds.Height - f.Height;
            int desksWidths = (Screen.PrimaryScreen.Bounds.Width - f.Width);
            f.Location = new System.Drawing.Point(desksWidths + 75, desksHeights / 2);
            HelpButton = false;
            this.Cursor = Cursors.Default;
        }






    }
}
